from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_redis import RedisChatMessageHistory
from langchain_openai import ChatOpenAI

from config.load_key import load_key

llm = ChatOpenAI(
    model="Qwen/Qwen2.5-7B-Instruct",
    api_key=load_key("siliconflow_api_key"),
    base_url=load_key("siliconflow_base_url"),
)

# InMemoryChatMessageHistory 是基于内存的聊天记录，进程结束就清理掉了 是 BaseChatMessageHistory的子类
#history = InMemoryChatMessageHistory()

history = RedisChatMessageHistory(session_id="test", redis_url=load_key("REDIS_URL"))
# 第一轮聊天
history.add_user_message("当我问你是谁时，你要回答 ‘我是妲己，我可以为主人做什么？’")
ai_message = llm.invoke(history.messages)
print(ai_message.content)
history.add_message(ai_message)
# 第二轮对话
history.add_user_message("你是谁？")
ai_message2 = llm.invoke(history.messages)
print(ai_message2.content)
history.add_message(ai_message2)
# 第三轮聊天
history.add_user_message("请重复一次")
ai_message3 = llm.invoke(history.messages)
print(ai_message3.content)
history.add_ai_message(ai_message3)

# 打印历史聊天记录
print("聊天历史：")
for message in history.messages:
    print(f"{type(message).__name__}: {message.content}")

